// 获取本地的配置

import ConfigManager, { type LoginConfig } from '../config/configManager'
import MachineInfo from './machineInfo'
import logger from '../logger'

const API_URL =
  'https://env-00jxu65bfie3.dev-hz.cloudbasefunction.cn/http/router/admin/card/pub/verify'

// 产品ID配置（与前端配置保持一致）
const PRODUCT_ID = 'exe-jd-data-assistant'

/* 检查VIP 获取用户id 和 用户密钥 

返回成功示例：{ code: 0, result: true, msg: 'VIP校验成功' }
返回失败示例：{ code: -1, result: false, msg: 'VIP用户ID或密钥未配置' }

*/

export async function checkVIP(
  override = { vipUserId: '', vipUserKey: '' }
): Promise<{ code: number; result: boolean; msg: string }> {
  try {
    const configManager = new ConfigManager()
    const saved = configManager.getConfig('login') as LoginConfig
    // 修复字段映射：从login配置中读取loginId和loginKey作为VIP参数
    const vipUserId = override?.vipUserId ?? saved.loginId ?? ''
    const vipUserKey = override?.vipUserKey ?? saved.loginKey ?? ''

    // console.log('🔍 VIP校验参数:', { vipUserId, vipUserKey: vipUserKey ? '***' : 'empty' })
    logger.debug(`VIP校验参数: 用户ID=${vipUserId}, 密钥=${vipUserKey ? '***' : 'empty'}`)

    // 检查必要参数
    if (!vipUserId || !vipUserKey) {
      // console.warn('⚠️ VIP参数缺失:', { vipUserId: !!vipUserId, vipUserKey: !!vipUserKey })
      logger.warn(`VIP参数缺失: 用户ID=${!!vipUserId}, 密钥=${!!vipUserKey}`)
      return { code: 400, result: false, msg: 'VIP用户ID或密钥未配置' }
    }

    // 获取机器信息
    const machineInfo = new MachineInfo()
    const uuid = machineInfo.getUUID()
    logger.debug('机器信息:', { uuid })

    const myHeaders = new Headers()
    myHeaders.append('Content-Type', 'application/json')

    const raw = JSON.stringify({
      key: vipUserKey,
      product_id: PRODUCT_ID,
      id: vipUserId,
      machineCode: uuid
    })

    logger.debug('VIP校验原始数据:', { raw })

    const requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw
    }

    logger.debug(`发送VIP校验请求到: ${API_URL}`)

    const res = await fetch(API_URL, requestOptions)
    const data = await res.json()

    logger.info(`VIP校验响应: code=${data.code}, msg=${data.msg}`)

    // 统一返回格式
    if (data.code === 0) {
      return { code: 0, result: true, msg: data.msg || '校验成功' }
    } else {
      return { code: data.code || -1, result: false, msg: data.msg || '校验失败' }
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    logger.error(`VIP校验异常: ${errorMessage}`)
    return { code: 500, result: false, msg: `VIP校验异常: ${String(error)}` }
  }
}

// 简单的VIP校验结果TTL缓存（毫秒）
let lastVipCheckResult: { code: number; result: boolean; msg: string } | null = null
let lastVipCheckAt = 0

export function updateVipCache(result: { code: number; result: boolean; msg: string }): void {
  lastVipCheckResult = result
  lastVipCheckAt = Date.now()
}

export async function checkVIPCached(
  ttlMs = 60000
): Promise<{ code: number; result: boolean; msg: string }> {
  const now = Date.now()
  if (lastVipCheckResult && now - lastVipCheckAt < ttlMs) {
    return lastVipCheckResult
  }
  const fresh = await checkVIP()
  updateVipCache(fresh)
  return fresh
}
